<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('单词背诵列表')" />
</head>
<body class="gray-bg">
     <div class="container-div">
        <div class="row">
            <div class="col-sm-12 search-collapse">
                <form id="formId">
                    <div class="select-list">
                        <ul>
                            <li>
                                <label>单词外文：</label>
                                <input type="text" name="name"/>
                            </li>
                            <li>
                                <label>中文翻译：</label>
                                <input type="text" name="meaning"/>
                            </li>
                            <li>
                                <label>分组值：</label>
                                <input type="text" name="value"/>
                            </li>
                            <li>
                                <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i class="fa fa-search"></i>&nbsp;搜索</a>
                                <a class="btn btn-warning btn-rounded btn-sm" onclick="$.form.reset()"><i class="fa fa-refresh"></i>&nbsp;重置</a>
                            </li>
                        </ul>
                    </div>
                </form>
            </div>

            <div class="btn-group-sm" id="toolbar" role="group">
                <a class="btn btn-warning" data-export shiro:hasPermission="student:get:export">
                    <i class="fa fa-download"></i> 导出
                </a>
            </div>
            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table"></table>
            </div>
        </div>
    </div>
    <th:block th:include="include :: footer" />
    <script th:inline="javascript">
        var editFlag = [[${@permission.hasPermi('student:get:edit')}]];
        var removeFlag = [[${@permission.hasPermi('student:get:remove')}]];
        var statusDatas = [[${@dict.getType('word_status')}]];
        var prefix = ctx + "student/get";

        $(function() {
            var options = {
                url: prefix + "/list",
                createUrl: prefix + "/add",
                updateUrl: prefix + "/edit/{id}",
                removeUrl: prefix + "/remove",
                exportUrl: prefix + "/export",
                modalName: "单词背诵",
                columns: [
                {
                    field: 'id',
                    title: '主键',
                    visible: false
                },
                {
                    field: 'name',
                    title: '单词外文'
                },
                {
                    field: 'meaning',
                    title: '中文翻译'
                },
                {
                    field: 'etymology',
                    title: '词源'
                },
                {
                    field: 'partOfSpeech',
                    title: '词性'
                },
                {
                    field: 'image',
                    title: '图片',
                    formatter: function(value, row, index) {
                        return value ? '<img src="' + value + '" style="width:50px; height:auto;">' : '暂无图片';
                    }
                },
                {
                    field: 'sound',
                    title: '语音',
                    formatter: function(value, row, index) {
                        return value ? `
                            <audio id="audio-${row.id}" src="${value}" preload="none"></audio>
                            <button class="btn btn-primary btn-xs" onclick="document.getElementById('audio-${row.id}').play()">
                                <i class="fa fa-play"></i> 播放
                            </button>
                        ` : '暂无语音';
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function(value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-remove"></i>删除</a>');
                        return actions.join('');
                    }
                },
                {
                    field: 'isCollected',
                    title: '收藏',
                    align: 'center',
                    formatter: function(value, row, index) {
                        return '<a class="btn btn-xs btn-collect" data-word-id="' + row.id + '">' +
                            '<i class="fa ' + (value ? 'fa-star' : 'fa-star-o') + '"></i></a>';
                    }
                }],
                showRefresh: false,
                showToggle: false,
                showColumns: false,
                sidePagination: "client",  // 新增客户端分页
                queryParams: function(params) {
                    // 保留原有查询参数处理
                    return $.table.queryParams(params);
                }
            };
            // 设置导出处理函数
            function exportData() {
                // 防止重复提交
                const exportBtn = $('[data-export]');
                if (exportBtn.hasClass('disabled')) {
                    return;
                }

                exportBtn.addClass('disabled');
                // 显示加载状态
                $.modal.loading("正在导出数据，请稍候...");

                const form = $('<form>', {
                    method: 'POST',
                    action: options.exportUrl,
                    style: 'display:none'
                }).appendTo('body');

                // 提交表单
                form.submit();

                // 重置按钮状态（可能需要服务器端配合）
                setTimeout(() => {
                    exportBtn.removeClass('disabled');
                    $.modal.closeLoading();
                }, 2000);
            }

            $.table._remove = $.table.remove;
            $.table.remove = function(id) {
                // 阻止默认删除逻辑
                var options = {
                    url: $.table._option.removeUrl,
                    type: "POST",
                    dataType: "json",
                    data: { ids: id },
                    success: function(result) {
                        if (result.code === 0) {
                            // 精确移除指定ID的行
                            $('#bootstrap-table').bootstrapTable('remove', {
                                field: 'id',
                                values: [id],
                                silent: true  // 防止触发表格事件
                            });
                            $.modal.msgSuccess(result.msg || "删除成功");
                            // 手动更新分页信息
                            var $table = $('#bootstrap-table');
                            $table.bootstrapTable('refreshOptions', {
                                totalRows: $table.bootstrapTable('getData').length
                            });
                        } else {
                            $.modal.alertError(result.msg);
                        }
                    }
                };
                // 显式发送请求并阻止默认行为
                $.ajax(options);
                return false; // 阻止事件冒泡
            };

            // 事件委托处理收藏按钮点击
            $(document).on('click', '.btn-collect', function() {
                var wordId = $(this).data('word-id');
                var $btn = $(this);
                $.ajax({
                    url: prefix + "/collect/" + wordId,
                    type: "POST",
                    success: function(result) {
                        var $icon = $btn.find('i');
                        $icon.toggleClass('fa-star fa-star-o');
                        $.modal.msgSuccess(result.msg || ($icon.hasClass('fa-star') ? "收藏成功" : "取消收藏"));
                    },
                    error: function(xhr) {
                        $.modal.alertError("操作失败: " + (xhr.responseJSON ? xhr.responseJSON.error : "服务器异常"));
                    }
                });
            });

            // 全局错误监听器
            $(document).ajaxError(function(event, jqxhr, settings, exception) {
                if (settings.url.includes("export")) {
                    $.modal.closeLoading();
                    $('[data-export]').removeClass('disabled');
                    $.modal.alertError("导出失败：" + exception);
                }
            });

            // 网络错误监听
            window.addEventListener('offline', function() {
                $.modal.alertWarning("网络已断开，请检查网络连接");
            });

            // 绑定点击事件
            $('[data-export]').on('click', exportData);
            options.exportHandler = exportData;
            $.table.init(options);
        });
    </script>
     <div class="review-container">
         <button class="btn btn-primary" th:onclick="|location.href='@{/student/get/review}'|">
             开始背诵
         </button>
     </div>

    <style>.review-container {
        display: flex;
        justify-content: center;
        margin-top: 30px;
    }
    </style>
</body>
</html>